package com.haohan.jingyuan.customer.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haohan.jingyuan.common.enums.ErrorEnum;
import com.haohan.jingyuan.common.exception.BusinessException;
import com.haohan.jingyuan.common.util.EntityUtil;
import com.haohan.jingyuan.customer.dao.CustomerIncomeMapper;
import com.haohan.jingyuan.customer.dao.CustomerInfoMapper;
import com.haohan.jingyuan.customer.dao.CustomerIncomeTypeMapper;
import com.haohan.jingyuan.customer.dto.req.CreateIncomeRequest;
import com.haohan.jingyuan.customer.dto.req.DeleteIncomeRequest;
import com.haohan.jingyuan.customer.dto.req.QueryIncomeListRequest;
import com.haohan.jingyuan.customer.dto.req.UpdateIncomeRequest;
import com.haohan.jingyuan.customer.dto.resp.IncomeInfoResp;
import com.haohan.jingyuan.customer.dto.resp.IncomeListResp;
import com.haohan.jingyuan.customer.entity.CustomerIncome;
import com.haohan.jingyuan.customer.entity.CustomerInfo;
import com.haohan.jingyuan.customer.entity.CustomerIncomeType;
import com.haohan.jingyuan.customer.helper.IncomeRespHelper;
import com.haohan.jingyuan.gateway.holder.UserContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 客户收入服务实现类
 *
 * @ClassName CustomerIncomeService
 * @Description 客户收入相关业务逻辑实现
 * @Author hexijun
 * @Time 2025/01/19 16:00
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerIncomeService {

    /**
     * 客户收入Mapper
     */
    private final CustomerIncomeMapper customerIncomeMapper;

    /**
     * 客户信息Mapper
     */
    private final CustomerInfoMapper customerInfoMapper;

    /**
     * 客户收入类型Mapper
     */
    private final CustomerIncomeTypeMapper customerIncomeTypeMapper;

    /**
     * 创建收入记录
     *
     * @param request 创建收入请求
     * @return 收入信息
     */
    public IncomeInfoResp createIncome(CreateIncomeRequest request) {
        // 校验客户是否存在
        CustomerInfo customerInfo = customerInfoMapper.findByCustomerId(request.getCustomerId());
        if (customerInfo == null) {
            throw new BusinessException(ErrorEnum.CUSTOMER_NOT_FOUND);
        }

        // 校验收入类型是否存在
        CustomerIncomeType incomeType = customerIncomeTypeMapper.findByType(request.getIncomeType());
        if (incomeType == null) {
            throw new BusinessException(ErrorEnum.INCOME_TYPE_NOT_FOUND);
        }

        // 校验待收金额计算是否正确（待收金额 = 总价金额 - 已收金额）
        BigDecimal calculatedPendingAmount = request.getTotalAmount().subtract(request.getReceivedAmount());
        if (calculatedPendingAmount.compareTo(request.getPendingAmount()) != 0) {
            throw new BusinessException(ErrorEnum.INCOME_AMOUNT_ERROR);
        }

        // 创建收入记录
        CustomerIncome customerIncome = new CustomerIncome();
        customerIncome.setCustomerId(request.getCustomerId());
        customerIncome.setIncomeType(request.getIncomeType());
        customerIncome.setTotalAmount(request.getTotalAmount());
        customerIncome.setReceivedAmount(request.getReceivedAmount());
        customerIncome.setPendingAmount(request.getPendingAmount());
        customerIncome.setIncomeDate(new Date());
        customerIncome.setRemarks(request.getRemarks());
        EntityUtil.setCreateAndModifyInfo(customerIncome, UserContextHolder.getCurrentUserName());

        // 保存到数据库
        int result = customerIncomeMapper.insert(customerIncome);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }
        return IncomeRespHelper.convert2IncomeInfoResp(customerIncome);
    }

    /**
     * 更新收入记录
     *
     * @param request 更新收入请求
     * @return 收入信息
     */
    public IncomeInfoResp updateIncome(UpdateIncomeRequest request) {
        // 查询收入记录是否存在
        Long id = Long.parseLong(request.getId());
        CustomerIncome customerIncome = customerIncomeMapper.selectById(id);
        if (customerIncome == null) {
            throw new BusinessException(ErrorEnum.INCOME_NOT_FOUND);
        }

        // 校验收入类型是否存在（如果传入了收入类型）
        if (request.getIncomeType() != null && !request.getIncomeType().trim().isEmpty()) {
            CustomerIncomeType incomeType = customerIncomeTypeMapper.findByType(request.getIncomeType());
            if (incomeType == null) {
                throw new BusinessException(ErrorEnum.INCOME_TYPE_NOT_FOUND);
            }
        }

        // 更新收入记录信息
        if (request.getIncomeType() != null) {
            customerIncome.setIncomeType(request.getIncomeType());
        }
        if (request.getTotalAmount() != null) {
            customerIncome.setTotalAmount(request.getTotalAmount());
        }
        if (request.getReceivedAmount() != null) {
            customerIncome.setReceivedAmount(request.getReceivedAmount());
        }
        if (request.getPendingAmount() != null) {
            customerIncome.setPendingAmount(request.getPendingAmount());
        }
        if (request.getIncomeDate() != null) {
            customerIncome.setIncomeDate(request.getIncomeDate());
        }
        if (request.getRemarks() != null) {
            customerIncome.setRemarks(request.getRemarks());
        }

        // 如果更新了金额相关字段，需要校验待收金额计算是否正确
        if (request.getTotalAmount() != null || request.getReceivedAmount() != null || request.getPendingAmount() != null) {
            BigDecimal calculatedPendingAmount = customerIncome.getTotalAmount().subtract(customerIncome.getReceivedAmount());
            if (calculatedPendingAmount.compareTo(customerIncome.getPendingAmount()) != 0) {
                throw new BusinessException(ErrorEnum.INCOME_AMOUNT_ERROR);
            }
        }

        // 设置修改信息
        EntityUtil.setModifyInfo(customerIncome, UserContextHolder.getCurrentUserName());

        // 更新数据库
        int result = customerIncomeMapper.updateById(customerIncome);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }

        IncomeInfoResp incomeInfoResp = IncomeRespHelper.convert2IncomeInfoResp(customerIncome);
        return incomeInfoResp;
    }

    /**
     * 查询收入列表
     *
     * @param request 查询收入列表请求
     * @return 收入列表
     */
    public IncomeListResp queryIncomeList(QueryIncomeListRequest request) {

        // 如果传入了客户ID，校验客户是否存在
        if (request.getCustomerId() != null && !request.getCustomerId().trim().isEmpty()) {
            CustomerInfo customerInfo = customerInfoMapper.findByCustomerId(request.getCustomerId());
            if (customerInfo == null) {
                throw new BusinessException(ErrorEnum.CUSTOMER_NOT_FOUND);
            }
        }

        // 创建分页对象
        Page<CustomerIncome> page = new Page<>(request.getPageNum(), request.getPageSize());

        // 分页查询收入列表
        IPage<CustomerIncome> incomePage = customerIncomeMapper.selectIncomeListPage(
                page, 
                request.getIncomeType(), 
                request.getCustomerId(), 
                request.getIncomeDateStart(), 
                request.getIncomeDateEnd());

        // 转换为响应对象
        List<IncomeInfoResp> incomeInfoList = new ArrayList<>();
        for (CustomerIncome record : incomePage.getRecords()) {
            incomeInfoList.add(IncomeRespHelper.convert2IncomeInfoResp(record));
        }

        // 查询所有符合条件的收入记录用于计算汇总字段（所有数据的汇总，不仅仅是当前页）
        // 使用相同的查询条件，但不分页
        Page<CustomerIncome> allPage = new Page<>(1, Integer.MAX_VALUE);
        IPage<CustomerIncome> allIncomePage = customerIncomeMapper.selectIncomeListPage(
                allPage, 
                request.getIncomeType(), 
                request.getCustomerId(), 
                request.getIncomeDateStart(), 
                request.getIncomeDateEnd());

        BigDecimal totalReceivable = BigDecimal.ZERO;
        BigDecimal totalReceived = BigDecimal.ZERO;
        BigDecimal totalPending = BigDecimal.ZERO;

        for (CustomerIncome record : allIncomePage.getRecords()) {
            // 累加汇总字段
            if (record.getTotalAmount() != null) {
                totalReceivable = totalReceivable.add(record.getTotalAmount());
            }
            if (record.getReceivedAmount() != null) {
                totalReceived = totalReceived.add(record.getReceivedAmount());
            }
            if (record.getPendingAmount() != null) {
                totalPending = totalPending.add(record.getPendingAmount());
            }
        }

        IncomeListResp response = new IncomeListResp();
        response.setIncomeList(incomeInfoList);
        response.setTotalReceivable(totalReceivable);
        response.setTotalReceived(totalReceived);
        response.setTotalPending(totalPending);
        response.setTotal(incomePage.getTotal());
        response.setPageNum(request.getPageNum());
        response.setPageSize(request.getPageSize());
        response.setTotalPages((int) incomePage.getPages());

        log.info("CustomerIncomeService.queryIncomeList SUCCESS ==> total: {}, pageNum: {}, pageSize: {}, totalPages: {}", 
                incomePage.getTotal(), request.getPageNum(), request.getPageSize(), incomePage.getPages());
        return response;
    }

    /**
     * 删除收入记录
     *
     * @param request 删除收入请求
     * @return 删除结果
     */
    public boolean deleteIncome(DeleteIncomeRequest request) {
        // 查询收入记录是否存在
        Long id = Long.parseLong(request.getId());
        CustomerIncome customerIncome = customerIncomeMapper.selectById(id);
        if (customerIncome == null) {
            throw new BusinessException(ErrorEnum.INCOME_NOT_FOUND);
        }

        // 逻辑删除
        customerIncome.setIsDeleted("Y");
        EntityUtil.setModifyInfo(customerIncome, UserContextHolder.getCurrentUserName());

        // 更新数据库
        int result = customerIncomeMapper.updateById(customerIncome);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }
        return true;
    }
}
